import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';

Vue.use(Vuex);

const routers = {
  namespaced: true,
  state: () => ({
    routers: '',
    token: '',
    userInfo: {},
  }),
  mutations: {
    routers(state, newsdata) {
      state.routers = newsdata;
    },
    setToken(state, value) {
      state.token = value;
    },
    setUserInfo(state, value) {
      state.userInfo = JSON.parse(JSON.stringify(value));
      console.log(state.userInfo);
    },
  },
  actions: {
    routers(context) {
      context.commit('routers');
    },
  },
  getters: {
    routers(state) {
      return state.routers;
    },
  },
};

export default new Vuex.Store({
  modules: {
    routers: routers,
  },
  plugins: [
    createPersistedState({
      storage: window.sessionStorage, // 默认位置是 localStorage
      reducer: (state) => {
        return {
          // 默认是全部缓存，在这里可以设置需要缓存的状态
          token: state.token,
          routers: state.routers,
          userInfo: state.userInfo,
        };
      },
    }),
  ],
});
